﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;

namespace YJKOpeningDesignInput.Public
{
	internal class GridData
	{
		private static bool GetFirstGrids(List<Document> lstDoc, ref List<Grid> lstGrid)
		{
			bool result;
			try
			{
				foreach (Autodesk.Revit.DB.Document document in lstDoc)
				{
					foreach (Element element in new FilteredElementCollector(document).OfClass(typeof(Grid)).WhereElementIsNotElementType().ToElements())
					{
						Grid grid = element as Grid;
						if (grid != null)
						{
							lstGrid.Add(grid);
						}
					}
					if (lstGrid.Count != 0)
					{
						break;
					}
				}
				result = true;
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		public static bool GetGridInfos(List<Document> lstDoc, ref List<PointSort> lstInfos)
		{
			List<Grid> list = new List<Grid>();
			if (!GridData.GetFirstGrids(lstDoc, ref list))
			{
				return false;
			}
			if (list.Count == 0)
			{
				return true;
			}
			int count = list.Count;
			for (int i = 0; i < count - 1; i++)
			{
				for (int j = i + 1; j < count; j++)
				{
					if (!(list[i].Name == list[j].Name))
					{
						Curve curve = list[i].Curve;
						Curve curve2 = list[j].Curve;
						IntersectionResultArray intersectionResultArray = null;
                        if ((int)curve.Intersect(curve2, out intersectionResultArray) == 8)
						{
							PointSort pointSort = new PointSort();
							XYZ xyzpoint = intersectionResultArray.get_Item(0).XYZPoint;
							pointSort.m_pt = new XYZ(xyzpoint.X, xyzpoint.Y, 0.0);
							if (GridData.IsStringHaveAscII(list[i].Name))
							{
								pointSort.m_lstGridName.Add(list[i].Name);
								pointSort.m_lstGridName.Add(list[j].Name);
							}
							else
							{
								pointSort.m_lstGridName.Add(list[j].Name);
								pointSort.m_lstGridName.Add(list[i].Name);
							}
							lstInfos.Add(pointSort);
						}
					}
				}
			}
			return true;
		}

		private static bool IsStringHaveAscII(string strVal)
		{
			try
			{
				foreach (char c in strVal)
				{
					if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
					{
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}
	}
}
